<template>
  <div class="login-container">
    <!-- navbar -->
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="phone"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对'
          }
        ]"
      />
      <van-field
        v-model="code"
        type="password"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="加载中..."
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入login.js
import { userLogin } from '@/api/login.js'
import { saveToken } from '@/utils/token.js'
export default {
  name: 'login',
  data () {
    return {
      phone: '13662613212',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    onSubmit (values) {
      // console.log('submit', values)
      this.isLoading = true
      userLogin(values)
        .then(res => {
          console.log(res)
          this.$toast.success('登录成功')
          saveToken(res.data.data)
          // 点击登录跳转到上一页
          // this.$router.push('/')
          this.$router.back()
        })
        .catch(err => {
          console.log(err)
          this.$toast.fail('登录失败')
        })
        .finally(() => {
          this.isLoading = false
        })
    }
  }
}
</script>

<style lang="less">
.van-nav-bar {
  .van-nav-bar__content {
    background-color: #3196fa;
  }
  .van-nav-bar__title {
    color: #fff;
  }
  .van-nav-bar__text,
  .van-icon.van-icon-arrow-left {
    color: white;
  }
}
</style>
